<?php

namespace CSan\NutrientBundle\Entity;

class AbstractRepository extends \Doctrine\ORM\EntityRepository
{	
    public function createQueryBuilder($alias = '_e', array $params = array())
    {		
        $qb = parent::createQueryBuilder($alias);

        // publicId
        if (isset($params['publicId']) AND !empty($params['publicId'])) {
            $qb->andWhere($alias . '.publicId = :publicId')
                ->setParameter('publicId', $params['publicId']);
        }

        // limit & offset
        if (isset($params['limit']) AND $params['limit'] >= 0) {
            $qb->setMaxResults($params['limit']);
            if (isset($params['offset']) AND $params['offset'] >= 0) {
                $qb->setFirstResult($params['offset']);
            }
        }

        // orderBy
        if (isset($params['orderBy']) AND is_array($params['orderBy'])) {
            foreach ($params['orderBy'] as $item) {
                $qb->addOrderBy($alias . '.' . $item['property'], $item['direction']);
            }
        }

        return $qb;
    }

    public function findAll(array $params = array())
    {
        $qb = $this->createQueryBuilder('_e', $params);
        return $qb->getQuery()->getResult();
    }

    public function findOne(array $params = array())
    {
        $params['limit'] = 1;
        $qb = $this->createQueryBuilder('_e', $params);
        return $qb->getQuery()->getSingleResult();
    }

    public function countAll(array $params = array())
    {
        $qb = $this->createQueryBuilder('_e', $params);
        $qb->select($qb->expr()->countDistinct('_e'));
        return $qb->getQuery()->getSingleScalarResult();
    }
}